"""
_*_ : utf-8 _*_ 
@Time: 2023/11/11 18:16
@Author: LWK
@File: 072_下载站长之家图片
@Project: demo01
"""
import urllib.request
from lxml import etree

# https://sc.chinaz.com/tupian/katongtupian.html
# https://sc.chinaz.com/tupian/katongtupian_2.html

BASE_URL = 'https://sc.chinaz.com'
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76'
}


def creat_req(page):
    if page != 1:
        url = BASE_URL + '/tupian/katongtupian_%s.html' % (str(page))
    else:
        url = BASE_URL + '/tupian/katongtupian.html'
    return urllib.request.Request(url=url, headers=headers)
    pass


def get_content(request):
    response = urllib.request.urlopen(request)
    return response.read().decode('utf-8')
    pass


def down_load_img (content):
    # 解析服务器响应文件
    tree = etree.HTML(content)
    # 获取想要的数据1
    alts = tree.xpath('//div[contains(@class, "tupian-list")]//img/@alt')
    srcs = tree.xpath('//div[contains(@class, "tupian-list")]//img/@data-original')
    for i in range(len(alts)):
        urllib.request.urlretrieve('http:' + srcs[i], '../temp/imges/072/' + alts[i] + '.jpg')
    pass


if __name__ == '__main__':
    print('下载站长之家卡通素材图片')
    s_page = int(input('请输入起始页码:'))
    e_page = int(input('请输入结束页码:'))
    for i in range(s_page, e_page + 1):
        # 请求对象定制
        req = creat_req(i)
        # 获取源码
        res = get_content(req)
        # 下载图片
        down_load_img(res)
